package framework

import (
	"database/sql"
	"fmt"
	"hsy/server/conf"
	"hsy/server/util"
	"log"

	//database driver
	_ "github.com/go-sql-driver/mysql"
)

var (
	//DB databse handler
	DB *sql.DB
)

/*
Init init DB and Conf
*/
func init() {
	initDB()
	InitDbTable()
}

func initDB() {

	//构建连接："用户名:密码@tcp(IP:端口)/数据库?charset=uft8"
	//注意：要想解析time.Time类型，必须要设置parseTime=True
	dataSourceName := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True", conf.DB_USER, conf.DB_PASS, conf.DB_HERF, conf.DB_PORT, conf.DB_NAME)
	DB, _ = sql.Open(conf.DB_DRIVER, dataSourceName)

	//设置数据库最大连接数
	//DB.SetConnMaxLifetime(100)
	//设置数据库最大闲置连接数
	//DB.SetMaxIdleConns(10)

	//验证连接
	if err := DB.Ping(); err != nil {
		log.Panic("database connect error")
	}

	log.Println("database connect successful")
}

/*
InitDbTable ...
*/
func InitDbTable() {
	var table string
	buffer, err := util.ReadConfFile(conf.DATABASE_CONF_PATH)
	if err != nil {
		fmt.Println("read error")
	}
	fmt.Println(buffer)
	for _, v := range buffer {
		if v != "" {
			table += v
		} else {
			_, err := DB.Exec(table)
			if err != nil {
				log.Panicf("create table to database occur error:%s", err.Error())
				break
			}
			log.Println("create a table to database is succeed.")
			table = ""
		}

	}

}
